package com.xizi.a_mianshi;

/**
 * @author xizizzz
 * @description: DCL Double Check Lock 双端检锁机制
 * @date 2021-7-8上午 11:44
 */
public class SingletonDemo2 {
    private static volatile SingletonDemo2 instance = null;

    private SingletonDemo2() {
        System.out.println(Thread.currentThread().getName() + "\t 我是构造方法SingletonDemo");
    }

    // DCL Double Check Lock 双端检锁机制
    public static SingletonDemo2 getInstance() {
        if (instance == null) {
            // 同步代码段的时候，进行检测
            synchronized (SingletonDemo2.class) {
                if (instance == null) {
                    instance = new SingletonDemo2();
                }
            }
        }
        return instance;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                SingletonDemo2.getInstance();
            }, String.valueOf(i)).start();
        }
    }
}
